package com.ossjk.api.controller;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.ossjk.core.base.controller.BaseController;
import com.ossjk.core.util.CommonMethod;
import com.ossjk.core.util.CommonUtil;
import com.ossjk.core.vo.ResponseBean;
import com.ossjk.oa.attendance.entity.Atdreport;
import com.ossjk.oa.attendance.service.IAtdreportService;
import com.ossjk.oa.system.entity.Department;
import com.ossjk.oa.system.service.IDepartmentService;
import com.ossjk.oa.system.service.IEmployeeService;
import com.ossjk.oa.system.service.IPostService;
import com.ossjk.oa.v_emp2dept.entity.V_emp2dept;
import com.ossjk.oa.v_emp2dept.service.V_emp2deptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;

/**
 * 吴非凡  “外出登记”模块
 */
@Api(description = "外出登记")
@RequestMapping("/api")
@RestController
public class OutregistrationController extends BaseController {
     @Autowired
    private IAtdreportService iAtdreportService;
    @Autowired
    private IEmployeeService iEmployeeService;
    @Autowired
    private IPostService iPostService;
    @Autowired
    private V_emp2deptService v_emp2deptService;
    @Autowired
    private IDepartmentService iDepartmentService;

    private Condition condition = Condition.create();

    //个人外出登记  参数为 eid  还有月份   type是5  5为外出登记类型112
	@ApiImplicitParams({
		@ApiImplicitParam(name = "date", value = "日期", paramType = "query", dataType = "String",required = true),
		@ApiImplicitParam(name = "eid", value = "用户id", paramType = "query", dataType = "String",required = true)
    })
    @ApiOperation(value = "通过日期和员工id查询员工个人信息  ", notes = "外出登记查询")
    @GetMapping("/getOutregistrationApplication")
    public ResponseBean<List<Atdreport>> getOutregistrationApplication(String date,String eid) {
        Wrapper wrapper = Condition.create().like("date", date).eq("type", 5).eq("eid", eid);

        return (ResponseBean<List<Atdreport>>) responseSuccess(iAtdreportService.selectList(wrapper));
    }

    //点击添加外出信息 会自动查询并返回这个员工所有信息
	@ApiOperation(value = "新增表的数据回显", notes = "需要将用户登录已经得到的数据回显")
    @GetMapping("toAddOutregistrationmess")
    public Object toAddOutregistrationmess() {
        String UserId = getCurrnetUserId();

        Wrapper wrapper = Condition.create().isWhere(true).eq("e.id", UserId);


        return responseSuccess(iEmployeeService.selectVo(wrapper));
    }




    //新增
    @ApiOperation(value = "新增外出登记表", notes = "新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "date", value = "外出日期", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "duration", value = "外出时长", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "remarks", value = "外出备注", paramType = "query", dataType = "String")
    })
    @PostMapping("/insertEgress")
    public ResponseBean insertEgress(@ApiIgnore Atdreport atdreport) {
//        /**
//         * 员工id,并不是必填
//         */
        if (CommonUtil.isBlank(atdreport.getEid())) {
            atdreport.setEid(getCurrnetUserId());
        }
//        /**
//         * 部门id,并不是必填
//         */
        if (CommonUtil.isBlank(atdreport.getDid())) {
            // 查询该员工的部门
            Department department = iDepartmentService.selectByEid(getCurrnetUserId());
            // 设置部门id
            atdreport.setDid(department.getId());
        }
//        /**
//         * 日期，前端传的，是否必填：是
//         */
        if (CommonUtil.isBlank(atdreport.getDate())) {
            return (ResponseBean) responseFail("date：外出时间不能为空");
        }
        // 格式化Date 如: yyyyMMdd
        String dateStr = CommonUtil.date0(atdreport.getDate());
        // 年
        atdreport.setYear(dateStr.substring(0, 4));
        // 月
        atdreport.setMonth(dateStr.substring(4, 6));
        // 日
        atdreport.setDay(dateStr.substring(6, 8));
//        /**
//         * 类型：1-加班、2-带薪年假、3-带薪调休、4-普通请假，5-外出,并不是必填
//         */
        if (CommonUtil.isBlank(atdreport.getType())) {
            atdreport.setType(new BigDecimal(5));
        }
//        /**
//         * 备注:是否必填，不是
//         */
        //        /**
//         * 审核状态：1-待审核、2-通过、3-不通过，后台定义的,默认值
//         */
        atdreport.setRwst(new BigDecimal(1));

//        /**
//         * 时长，前端传的，是否必填：是
//         */
        if (CommonUtil.isBlank(atdreport.getDuration())) {
            return (ResponseBean) responseFail("duration：外出时长不能为空");
        }

        if (iAtdreportService.insert(atdreport)) {
            return (ResponseBean) responseSuccess();
        } else {
            return (ResponseBean) responseFail();
        }
    }

    //修改进行回显的数据查询
    @ApiOperation(value = "修改 查询回显数据", notes = "修改回显")

    @ApiImplicitParam(name = "id", value = "主键id", paramType = "query", dataType = "String")
    @GetMapping("/toUpdateEgress")
    public ResponseBean<Atdreport> toUpdateEgress(String id) {
        if (CommonUtil.isBlank(id)) {
            return (ResponseBean<Atdreport>) responseFail("Id:不能为空");
        }
        return (ResponseBean<Atdreport>) responseSuccess(iAtdreportService.selectById(id));

    }

    //修改页面
    @ApiOperation(value = "修改外出登记表", notes = "外出登记修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "date", value = "外出日期", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "duration", value = "外出时长", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "remarks", value = "外出备注", paramType = "query", dataType = "String")
    })
    @PutMapping("/updateEgress")
    public ResponseBean updateEgress(@ApiIgnore Atdreport atdreport) {

        //id必填
        if (CommonUtil.isBlank(atdreport.getId())) {
            return (ResponseBean) responseFail("id:不能为空");
        }
        //判断审核状态是否=1
        Atdreport atdreport1 = iAtdreportService.selectById(atdreport.getId());
        if (!CommonUtil.isEquals(atdreport1.getRwst(), 1)) {
            return (ResponseBean) responseFail("rwst:状态不是待审核，不能修改");
        }
        //        /**
//         * 员工id,并不是必填
//         */
        if (CommonUtil.isBlank(atdreport.getEid())) {
            atdreport.setEid(getCurrnetUserId());
        }
//        /**
//         * 部门id,并不是必填
//         */
        if (CommonUtil.isBlank(atdreport.getDid())) {
            // 查询该员工的部门
            Department department = iDepartmentService.selectByEid(getCurrnetUserId());
            // 设置部门id
            atdreport.setDid(department.getId());
        }
//        /**
//         * 日期，前端传的，是否必填：是
//         */
        if (CommonUtil.isBlank(atdreport.getDate())) {
            return (ResponseBean) responseFail("date：外出时间不能为空");
        }
        // 格式化Date 如: yyyyMMdd
        String dateStr = CommonUtil.date0(atdreport.getDate());
        // 年
        atdreport.setYear(dateStr.substring(0, 4));
        // 月
        atdreport.setMonth(dateStr.substring(4, 6));
        // 日
        atdreport.setDay(dateStr.substring(6, 8));
//        /**
//         * 类型：1-加班、2-带薪年假、3-带薪调休、4-普通请假，5-外出,并不是必填
//         */
        if (CommonUtil.isBlank(atdreport.getType())) {
            atdreport.setType(new BigDecimal(5));
        }
//        /**
//         * 备注:是否必填，不是
//         */


//        /**
//         * 审核状态：1-待审核、2-通过、3-不通过，后台定义的,默认值
//         */
        atdreport.setRwst(new BigDecimal(1));

//        /**
//         * 时长，前端传的，是否必填：是
//         */
        if (CommonUtil.isBlank(atdreport.getDuration())) {
            return (ResponseBean) responseFail("duration：外出时长不能为空");
        }

        if (iAtdreportService.updateById((atdreport))) {
            return (ResponseBean) responseSuccess();
        } else {
            return (ResponseBean) responseFail();
        }
    }

    //删除单条记录
	@ApiOperation(value = "根据id删除外出登记表", notes = "判断，删除未经过审批的表")
    @DeleteMapping("deleteOutregistrationmess")
    public Object deleteOutregistrationmess(String id) {
        System.out.println(id);
        //  Wrapper wrapper =condition.eq("id",id);
        System.out.println("11111111111111111");

        return responseSuccess(iAtdreportService.deleteById(id));
    }





    //批量删除记录  接收数组的参数
    //删除的原理就是把 isdelete字段 1的值改为 2  如果字段为空是输出不出来的
	@ApiOperation(value = "批量删除外出登记表", notes = "判断，删除未经过审批的表")
    @ApiImplicitParam(name="id" ,value = "数据id")
    @DeleteMapping("batchDeleteOutregistrationmess")
    public ResponseBean batchDeleteOutregistrationmess(String[] id) {
        String str = "";

        if(CommonUtil.isBlank(id)){
            return (ResponseBean) responseFail("id不能为空");
        }
        System.out.println("111111111111111");
        for (int i = 0; i < id.length; i++) {
            if (i != (id.length - 1)) {
                str += id[i] + ",";
            } else {
                str += id[i];
            }
        }
        System.out.println(str);

        Wrapper wrapper = Condition.create().in("id", str).eq("rwst", 1);
        if(iAtdreportService.delete(wrapper)){

            return (ResponseBean) responseSuccess();
        }else {
            return (ResponseBean) responseFail("rwst:状态不是待审核，不能删除");
        }

    }



    /** 
     * 二级部门领导(总监一级)可以按部门查本部门的月度外出申请
     */
    @ApiOperation(value = "按部门查月度外出申请接口", notes = "二级部门领导(总监一级)可以按部门查本部门的月度外出申请")
    @ApiImplicitParams({  @ApiImplicitParam(name = "month", value = "月份", paramType = "query", dataType = "String"),
                          @ApiImplicitParam(name = "eid", value = "员工id", paramType = "query", dataType = "String"),
                            @ApiImplicitParam(name = "did", value = "部门id", paramType = "query", dataType = "String")})

    @GetMapping("queryDept")
    public ResponseBean<List<Atdreport>> queryDept(String month,String eid, String did){
        String UserId= getCurrnetUserId();
        //        1、判断前端时候有传递，部门id，员工id，月份,如果都没有可以通过token获取用户id
        if (CommonUtil.isBlank(month)) {
            Calendar now = Calendar.getInstance();
            month = CommonMethod.calMth(0, now.getTime()); // 默认本月
        }
        if (CommonUtil.isBlank(eid)) {
            //默认自己的
            eid = getCurrnetUserId();
        }

        System.out.println(month);
        Wrapper wrapper =Condition.create().isWhere(true).eq("id",eid);
//        System.out.println(UserId);
//        EmployeeVo employeeVo = iEmployeeService.selectVo(wrapper);
//        System.out.println(employeeVo.getPid());
//        EmployeeVo employeeVo =  iEmployeeService.selectVo(wrapper);
//          List<String> list1= getPsub();
//        for (String o :  list1) {
//            System.out.println(o);
//        }
        V_emp2dept v_emp2dept = v_emp2deptService.selectById(wrapper);
        if (CommonUtil.isBlank(did)) {
            //默认自己的
            did = v_emp2dept.getDid();
        }
//        System.out.println(v_emp2dept.getLevel());

        if(v_emp2dept.getLevel()==2){
            System.out.println("2222");
            Wrapper wrapper1=Condition.create().isWhere(true).eq("type",new BigDecimal(5)).eq("a.did",v_emp2dept.getDid()).like("date", month).eq("e.id",eid).eq("a.isdelete",1);

          return   (ResponseBean<List<Atdreport>>) responseSuccess(iAtdreportService.selectVo(wrapper1)) ;

        }else if(v_emp2dept.getLevel()==1){
            System.out.println("111111");
//            System.out.println("222222");
            Wrapper wrapper1=Condition.create().isWhere(true).eq("type",new BigDecimal(5)).like("date", month).eq("a.did",did).eq("e.id",eid).eq("a.isdelete",1);
            return   (ResponseBean<List<Atdreport>>) responseSuccess(iAtdreportService.selectVo(wrapper1)) ;
        }else{
            System.out.println(333333);
            Wrapper wrapper1=Condition.create().isWhere(true).eq("type",new BigDecimal(5)).eq("e.id",eid).eq("a.isdelete",1)
                    .like("date", month);
            return   (ResponseBean<List<Atdreport>>)  responseSuccess(iAtdreportService.selectVo(wrapper1));
        }




    }

    @ApiOperation(value = "查询所有部门信息", notes = "查询所有部门信息")
    @GetMapping("queryAllDept")
    public ResponseBean<List<V_emp2dept>> queryAllDept(){
        Wrapper wrapper1=Condition.create();

        return (ResponseBean<List<V_emp2dept>>) responseSuccess(iDepartmentService.selectAllDept(wrapper1)) ;
    }

    @ApiOperation(value = "按照传入的部门id查询其部门下的所有人信息", notes = "按照传入的部门id查询其部门下的所有人信息")
    @ApiImplicitParam(name = "did", value = "部门id", paramType = "query", dataType = "String", required = true)
//    查询每个部门人数接口
    @GetMapping("queryDeptPer")
    public ResponseBean<List<V_emp2dept>> queryDept1(String did){
        Wrapper wrapper1=Condition.create().isWhere(true).eq("did",did);

        return (ResponseBean<List<V_emp2dept>>) responseSuccess(v_emp2deptService.selectByPer(wrapper1)) ;
    }


  //先查询出所有的未审批的外出登记表
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rwst", value = "审核状态：1-待审核、2-通过、3-不通过", paramType = "query", dataType = "String")
    })
    @ApiOperation(value = "查询 未审批的的外出登记表", notes = "未审批的的登记表")
    @GetMapping("/toApprovalEgress")
    public ResponseBean<List<Atdreport>> toApprovalEgress(String rwst) {

        Wrapper wrapper = Condition.create().eq("rwst", rwst);
        return (ResponseBean<List<Atdreport>>) responseSuccess(iAtdreportService.selectList(wrapper));
    }


    //审批请假申请
    @ApiOperation(value = "审批外出登记表", notes = "判断，审批未审批的表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id", value = "id", paramType = "query", dataType = "String"),
		@ApiImplicitParam(name = "rwst", value = "审核状态：1-待审核、2-通过、3-不通过", paramType = "query", dataType = "String"),
		@ApiImplicitParam(name = "rwrs", value = "审核原因", paramType = "query", dataType = "String")
    })
    @PutMapping("/approvalEgress")
    public ResponseBean approvalEgress(String id, String rwst, String rwrs) {
        Atdreport atdreport = iAtdreportService.selectById(id);
        atdreport.setRwst(new BigDecimal(rwst));
        atdreport.setRwrs(rwrs);
        return (ResponseBean) responseSuccess(iAtdreportService.updateById(atdreport));
    }


    //外出信息的月度导航
	@ApiOperation(value = "外出月度导航", notes = "传入mth属性--例如：mth=2020-07")
    @ApiImplicitParam(name = "mth", value = "年月日期", paramType = "query", dataType = "String")
    @GetMapping("/monthNavEgress")
    public ResponseBean<List<Atdreport>> monthNavEgress(String mth) {

        //Wrapper wrapper = Condition.create().like("month", mth).eq("type", 5);
        if (mth == null) {
            Calendar now = Calendar.getInstance();
            if (now.get(Calendar.DAY_OF_MONTH) > 20) {
                mth = CommonMethod.calMth(0, now.getTime()); // 默认本月
            } else {
                mth = CommonMethod.calMth(-1, now.getTime()); // 默认上月
            }
        }

        return (ResponseBean<List<Atdreport>>) responseSuccess(iAtdreportService.selectPreNext(mth));
    }

}
